// pages/phone_login/phone_login.js
// pages/personpage/personpage.js
let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    thirdLoginV2: '1',
    ipone: '',
    Locallogin: true, //本机号 一键登录
    isphone: false, //输入手机号
    isCode: false, //输入验证码
    Perfect: false, //完善信息
    Invitee: false, //邀请人
    PasswordLogin: false, //密码登录
    Retrieve: false, //找回密码
    // Retrieve: true, 
    inputLen: 4,
    iptValue: "",
    isFocus: false,
    ipone_Invitee: '', //邀请人id
    limitGetSmsCode: {
      enable: true,
      leftSeconds: 60,
      content: "获取验证码"
    },

    userInfo: {}, //用户信息
    nickname: "",
    autograph: "",
    sexList: ["男", "女"],
    sexindex: 0,
    birthday: "2021-5-10",
    headimg: "",
    ipone_one: '', //密码登录手机
    ipone_two: '', //密码登录密码
    ipone_three: '', //找回密码手机号
    ipone_four: '', //找回密码验证码
    ipone_five: '', //找回密码新密码
  },
  //获取本机手机号
  bindPhone(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      // console.log(e);
      this.oneStepLogin(e)
    } else {
      wx.showToast({
        title: '拒绝',
        icon: 'none',
        duration: 2000,
      })
    }
  },
  // 一键登录
  oneStepLogin(e) {
    wx.checkSession({
      success: function () {
        let promise = new Promise((resolve, reject) => {
          let _ = this;
          wx.login({ //获取code
            success: resCode => {
              let params = {
                code: resCode.code,
                type: "2",
              };
              axios.axios({
                url: "/index/getOpenId",
                data: params
              }).then((res) => {
                resolve(res.data.result)
                app.globalData.openid = res.data.result.openid;
                app.globalData.unionid = res.data.result.unionid;
                wx.setStorageSync('unionid', res.data.result.unionid)
              })
            }
          });
        })
        promise.then((res) => {
          let params = {
            sessionKey: res.session_key,
            iv: e.detail.iv,
            encryptedData: e.detail.encryptedData,
          };
          axios.axios({
            url: "/user/appletOneStepLogin",//一键登录
            data: params
          }).then((res2) => {
            if (res2.data.status == 0) {
              wx.setStorageSync('UserInformation', res2.data.result)
              app.globalData.user_id = res2.data.result.userId;
              app.globalData.userToken = res2.data.result.token;
              app.globalData.perfectNumber = res2.data.result.perfectNumber;
              setTimeout(function () {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }, 3000);
            } else {
              wx.showToast({
                title: res2.data.text,
                icon: 'none',
                duration: 3000
              })
            }
          })
        })
      },
      fail: function (res) {
        console.log("需要重新登录");
      }
    })

  },
  //切换手机号
  tab_isphone() {
    this.setData({
      Locallogin: false,
      isphone: true,
    })
  },
  //找回密码
  Retrieve_password() {
    this.setData({
      PasswordLogin: false,
      Retrieve: true,
    })
  },
  //密码登录
  PasswordLogin_true() {
    this.setData({
      PasswordLogin: true,
      isphone: false
    })
  },
  onFocus: function (e) {
    var that = this;
    that.setData({
      isFocus: true
    });
  },
  //验证码登录
  isphone_true() {
    this.setData({
      isphone: true,
      PasswordLogin: false
    })
  },
  setValue: function (e) {
    // console.log(e.detail.value);
    var that = this;
    that.setData({
      iptValue: e.detail.value
    });
    if (that.data.iptValue.length == '4') {
      this.codelogin()
    }
  },
  InviteeInput: function (e) {
    // console.log(e.detail.value);
    var that = this;
    that.setData({
      ipone_Invitee: e.detail.value
    });
  },
  fhui_() {
    wx.navigateBack({ //返回
      delta: 1
    })
  },
  iponeInput(data) {
    this.setData({
      ipone: data.detail.value
    })
  },
  iponeInput_one(data) {
    this.setData({
      ipone_one: data.detail.value
    })
  },
  iponeInput_two(data) {
    this.setData({
      ipone_two: data.detail.value
    })
  },
  iponeInput_three(data) {
    this.setData({
      ipone_three: data.detail.value
    })
  },
  iponeInput_four(data) {
    this.setData({
      ipone_four: data.detail.value
    })
  },
  iponeInput_five(data) {
    this.setData({
      ipone_five: data.detail.value
    })
  },
  //密码登录
  user_login() {
    let _ = this;
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      mobile: _.data.ipone_one,
      password: _.data.ipone_two,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let that = this;
    let params = {
      mobile: _.data.ipone_one,
      password: _.data.ipone_two,
      time: timestamp,
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/login",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000
        })
        wx.setStorageSync('UserInformation', res.data.result)
        app.globalData.user_id = res.data.result.userId;
        app.globalData.userToken = res.data.result.token;
        app.globalData.perfectNumber = res.data.result.perfectNumber;
        setTimeout(function () {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }, 3000);
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  getPhoneSmsByCode() {
    var _ = this;
    if (!_.data.limitGetSmsCode.enable) {
      wx.showToast({
        title: _.data.limitGetSmsCode.leftSeconds + "秒后重新获取",
        icon: 'none',
        duration: 1000
      })
      return
    }
    var limitGetSmsCode2 = _.data.limitGetSmsCode
    limitGetSmsCode2.enable = false
    _.setData({
      limitGetSmsCode: limitGetSmsCode2
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      phone: _.data.ipone,
      type: '5',
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      type: '5',
      phone: _.data.ipone,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/sendRegCode",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        _.checkGetSmsFreq();
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000
        })
        if (!this.data.isCode) {
          this.setData({
            isCode: true,
            isphone: false
          })
        }
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000
        })
        var limitGetSmsCode2 = _.data.limitGetSmsCode
        limitGetSmsCode2.enable = true
        _.setData({
          limitGetSmsCode: limitGetSmsCode2
        })
      }
    })
  },
  getPhoneSmsBType2() {
    var _ = this;
    if (!_.data.limitGetSmsCode.enable) {
      wx.showToast({
        title: _.data.limitGetSmsCode.leftSeconds + "秒后重新获取",
        icon: 'none',
        duration: 1000
      })
      return
    }
    var limitGetSmsCode2 = _.data.limitGetSmsCode
    limitGetSmsCode2.enable = false
    _.setData({
      limitGetSmsCode: limitGetSmsCode2
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      phone: _.data.ipone_three,
      type: '2',
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      type: '2',
      phone: _.data.ipone_three,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/sendRegCode",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        _.checkGetSmsFreq();
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000
        })
        var limitGetSmsCode2 = _.data.limitGetSmsCode
        limitGetSmsCode2.enable = true
        _.setData({
          limitGetSmsCode: limitGetSmsCode2
        })
      }
    })
  },
  checkGetSmsFreq() {
    var _ = this;
    var c = setInterval(function () {
      var limitGetSmsCode2 = _.data.limitGetSmsCode
      limitGetSmsCode2.content = --limitGetSmsCode2.leftSeconds + "秒后再获取";
      _.setData({
        limitGetSmsCode: limitGetSmsCode2
      })
      if (_.data.limitGetSmsCode.leftSeconds <= 0) {
        var limitGetSmsCode3 = _.data.limitGetSmsCode
        limitGetSmsCode3.content = "重新获取验证码";
        limitGetSmsCode3.leftSeconds = 60;
        _.setData({
          limitGetSmsCode: limitGetSmsCode3
        })
        clearInterval(c);
        _.data.limitGetSmsCode.enable = true;
        var limitGetSmsCode4 = _.data.limitGetSmsCode
        limitGetSmsCode4.enable = true;
        _.setData({
          limitGetSmsCode: limitGetSmsCode4
        })
      }
    }, 1000);
  },
  //密码登录
  forgetPassword() {
    let _ = this
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      phone: _.data.ipone_three,
      authCode: _.data.ipone_four,
      newPassword: _.data.ipone_five,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      phone: _.data.ipone_three,
      authCode: _.data.ipone_four,
      newPassword: _.data.ipone_five,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/forgetPassword",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.setData({
          Retrieve: false,
          PasswordLogin: true
        })
        // setTimeout(function () {
        //   wx.switchTab({
        //     url: '/pages/index/index',
        //   })
        // }, 2000);
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //验证码登录
  codelogin() {
    let _ = this
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      mobile: _.data.ipone,
      authCode: _.data.iptValue,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      mobile: _.data.ipone,
      authCode: _.data.iptValue,
      time: timestamp,
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/codelogin",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        if (res.data.result.firstReg == '1') {
          wx.setStorageSync('UserInformation', res.data.result)
          app.globalData.userInfo = res.data.result
          app.globalData.user_id = res.data.result.userId;
          app.globalData.userToken = res.data.result.token;
          app.globalData.perfectNumber = res.data.result.perfectNumber;
          wx.showToast({
            title: "注册成功",
            icon: 'none',
            duration: 2000
          })
          this.setData({
            userInfo: res.data.result,
            isCode: false,
            Perfect: true,
          })
          // this.open_user()
        } else {
          wx.setStorageSync('UserInformation', res.data.result)
          app.globalData.user_id = res.data.result.userId;
          app.globalData.userToken = res.data.result.token;
          app.globalData.perfectNumber = res.data.result.perfectNumber;
          wx.showToast({
            title: "登录成功",
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }, 3000);
        }
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  nicknameIpt(data) {
    this.setData({
      nickname: data.detail.value
    })
  },
  autographIpt(data) {
    this.setData({
      autograph: data.detail.value
    })
  },
  sexChange(data) {
    console.log('picker发送选择改变，携带值为', data.detail.value, parseInt(data.detail.value))
    this.setData({
      sexindex: data.detail.value
    })
  },
  birthdayChange(data) {
    console.log('picker发送选择改变，携带值为', data.detail.value)
    this.setData({
      birthday: data.detail.value
    })
  },
  chooseImg() {
    var _this = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        let timestamp = (Date.parse(new Date()) / 1000).toString();
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        wx.uploadFile({
          url: axios.testInterface + '/user/editUserProfile', //测试
          filePath: tempFilePaths[0],
          name: 'headPic',
          formData: {
            type: '1',
            userId: app.globalData.user_id,
            token: app.globalData.userToken,
            sex: parseInt(_this.data.sexindex) + 1,
            birthday: _this.data.birthday,
            nickname: _this.data.nickname,
            time: timestamp,
          },
          success(res) {
            console.log(res);
            _this.open_user()
          }
        })
      }
    })
  },
  //新用户注册
  reg(uner_info) {
    let promise = new Promise((resolve, reject) => {
      let _ = this;
      wx.login({ //获取code
        success: res => {
          let params = {
            code: res.code,
            type: "2",
          };
          axios.axios({
            url: "/index/getOpenId",
            data: params
          }).then((res) => {
            resolve(res.data.result)
            app.globalData.openid = res.data.result.openid;
            app.globalData.unionid = res.data.result.unionid;
            wx.setStorageSync('unionid', res.data.result.unionid)
          })

        }
      });
    })
    promise.then((res) => {
      console.log(res, uner_info);
      let params = {
        nickname: uner_info.nickName,
        sex: uner_info.gender,
        birthday: "1988-09-26",
        invitedId: this.data.ipone_Invitee,
        headpic: uner_info.avatarUrl,
        type: "1",
        unionid: res.unionid,
        openid: res.openid,
        shumeiDeviceId: wx.getStorageSync('shumeiDeviceId')
      };
      axios.axios({
        url: "/user/reg",
        data: params
      }).then((res) => {
        if (res.data.status == 0) {
          console.log(res);
          this.setData({
            thirdLoginV2: "1",
            Invitee: true,
            isphone: false
          })
        } else {
          app.user_info('1').then((res) => {
            if (res) {
              wx.showToast({
                title: '登录成功',
                icon: 'none',
                duration: 1000
              })
              setTimeout(function () {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }, 1000);
            } else {
              wx.showToast({
                title: "授权失败",
                icon: 'none',
                duration: 2000 //持续的时间
              })
            }
          }, (error) => {
            console.log('数据请求失败：' + error)
          })
        }
      })
    })
  },
  meansSub(data) {
    if (this.data.thirdLoginV2 == "index") { //微信新用户
      if (data.currentTarget.dataset.invitedid) { //点击完成
        if (!this.data.ipone_Invitee) {
          return wx.showToast({
            title: "请填入邀请人",
            icon: "none",
            duration: 2000
          })
        }
        wx.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            this.reg(res.userInfo) //注册
          }
        })
      } else { //跳过
        wx.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            this.reg(res.userInfo) //注册
          }
        })
      }
    } else {
      if (!this.data.nickname) {
        return wx.showToast({
          title: "请填入昵称",
          icon: "none",
          duration: 2000
        })
      }
      if (!this.data.headimg) {
        return wx.showToast({
          title: "请上传头像",
          icon: "none",
          duration: 2000
        })
      }
      if (this.data.thirdLoginV2 == '2') {
        if (data.currentTarget.dataset.invitedid) {
          if (!this.data.ipone_Invitee) {
            return wx.showToast({
              title: "请填入邀请人",
              icon: "none",
              duration: 2000
            })
          }
        }
      }
      let nickname = this.data.nickname;
      let sex = parseInt(this.data.sexindex) + 1;
      let birthday = this.data.birthday;
      let invitedId = this.data.ipone_Invitee;
      let headpic = this.data.headimg;
      app.wxzhuce(nickname, sex, birthday, invitedId, headpic)
      let timestamp = (Date.parse(new Date()) / 1000).toString();
      let _token =
        "userId=" +
        app.globalData.user_id +
        "&token=" +
        app.globalData.userToken +
        "&time=" +
        timestamp +
        "&sex=" +
        parseInt(this.data.sexindex) + 1 +
        "&originSign=" +
        this.data.autograph +
        "&nickName=" +
        this.data.nickname +
        "&invitedId=" +
        this.data.ipone_Invitee +
        "&headPic=" +
        this.data.headimg +
        "&birthday=" +
        this.data.headimg +
        "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
      let params = {
        invitedId: this.data.ipone_Invitee,
        userId: app.globalData.user_id,
        token: app.globalData.userToken,
        sex: parseInt(this.data.sexindex) + 1,
        originSign: this.data.autograph,
        birthday: this.data.birthday,
        nickName: this.data.nickname,
        headPic: this.data.headimg,
        time: timestamp,
        sign: md5.hexMD5(_token),
      };
      axios.axios({
        url: "/user/editUserProfile",
        data: params
      }).then((res) => {
        if (res.data.status == 0) {
          if (this.data.thirdLoginV2 == '1') {
            this.setData({
              thirdLoginV2: '2',
            })
          }
          wx.showToast({
            title: res.data.text,
            icon: "none",
            duration: 1000
          })
          if (this.data.Invitee) {
            wx.showToast({
              title: res.data.text,
              icon: 'none',
              duration: 1000
            })
            setTimeout(function () {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }, 3000);
          } else {
            this.setData({
              Perfect: false,
              Invitee: true
            })
          }
        } else {
          wx.showToast({
            title: res.data.text,
            icon: "none",
            duration: 1000
          })
        }
      })
    }
  },
  tomyalbum() {
    wx.navigateTo({
      url: '/pages/myalbum/myalbum',
    })
  },
  open_user() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/userInfo",
      data: params
    }).then((res) => {
      console.log(res.data.result),
        this.setData({
          userInfo: res.data.result.user,
          headimg: res.data.result.user.headPic
        })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */


  onLoad: function (options) {
    if (options.thirdLoginV2 == '1') {
      this.setData({
        thirdLoginV2: options.thirdLoginV2,
        Perfect: true,
        isphone: false
      })
    } else if (options.SignIn == 'index') {
      this.setData({
        thirdLoginV2: options.SignIn,
        Invitee: true,
        isphone: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
